package grammar.parser.stmt;

import error.processing.MyErrorProcessing;
import exp.parser.Cond;
import word.parser.WordElement;

public class IfStmt extends Stmt {
    private final Cond cond;
    private final Stmt ifStmt;
    private final Stmt elseStmt;

    public IfStmt(Cond cond, Stmt ifStmt, Stmt elseStmt) {
        this.cond = cond;
        this.ifStmt = ifStmt;
        this.elseStmt = elseStmt;
    }

    public static IfStmt buildIfStmt() {
        assert getAnalyzingWord().getType() == WordElement.WordType.IFTK;
        analyzeNextWord();
        assert getAnalyzingWord().getType() == WordElement.WordType.LPARENT;
        analyzeNextWord();
        Cond cond = Cond.buildCond();
        if (getAnalyzingWord().getType() != WordElement.WordType.RPARENT) {
            MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.j,
                    getAnalyzingWord(-1));
        } else {
            analyzeNextWord();
        }
        Stmt ifStmt = Stmt.buildStmt();
        Stmt elseStmt = null;
        if (getAnalyzingWord().getType() == WordElement.WordType.ELSETK) {
            analyzeNextWord();
            elseStmt = Stmt.buildStmt();
        }
        return new IfStmt(cond, ifStmt, elseStmt);
    }

    @Override
    public void execute() {
        int val = cond.getValue();
        if (val != 0) {
            ifStmt.execute();
        } else {
            if (elseStmt != null) {
                elseStmt.execute();
            }
        }
    }
}
